<template>
    <div>
      <treeselect
        :options="optionsMechanism"
        placeholder="select...."
        v-model="value"
        :multiple="true"
        style="width: 400px"
      />
    </div>
  </template>
  <script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    components: {
      Treeselect,
    },
    props: {
        value: {
            type:String,
            default:null
        },
        data: {
            type: Array,
            default: () => []
        }
    },
    data() {
      return {
        optionsMechanism: [],
        // value: null,
        // data: [
        //   { id: 1, name: "一年级" },
        //   { id: 2, parent_id: 1, name: "一年级1班" },
        //   { id: 7, parent_id: 2, name: "一年级1-1班" },
        //   { id: 8, parent_id: 2, name: "一年级1-2班" },
        //   { id: 3, parent_id: 1, name: "一年级2班" },
        //   { id: 4, name: "二年级" },
        //   { id: 5, parent_id: 4, name: "二年级1班" },
        //   { id: 6, parent_id: 4, name: "二年级2班" },
        //   { id: 9, name: "三年级" },
        //   { id: 10, parent_id: 9, name: "三年级1班" },
        //   { id: 11, parent_id: 9, name: "三年级2班" },
        //   { id: 12, parent_id: 11, name: "三年级2-1班" },
        //   { id: 13, parent_id: 11, name: "三年级2-2班" },
        //   { id: 14, parent_id: 11, name: "三年级2-2班" },
        // ],
      };
    },
    mounted() {
      this.getData();
    },
    methods: {
      //将平铺数据转换为树形结构数据
      getTrees(list, parent_id = 0) {
        let parentObj = {};
        list.forEach((o) => {
          parentObj[o.id] = o;
        });
        if (!parent_id) {
          return list
            .filter((o) => !parentObj[o.parent_id])
            .map((o) => ((o.children = this.getTrees(list, o.id)), o));
        } else {
          return list
            .filter((o) => o.parent_id == parent_id)
            .map((o) => ((o.children = this.getTrees(list, o.id)), o));
        }
      },
      //去除转换树形结构数据后存在的空children
      deleteChildren(arr) {
        let childs = arr;
        for (let i = childs.length; i--; i > 0) {
          if (childs[i].children) {
            if (childs[i].children.length) {
              this.deleteChildren(childs[i].children);
            } else {
              delete childs[i].children;
            }
          }
        }
        return arr;
      },
      getData() {
        let data = this.data;
        data = data.map((item) => {
          return {
            id: item.id,
            parent_id: item.parent_id,
            label: item.name,
          };
        });
        this.optionsMechanism = this.deleteChildren(this.getTrees(data));
      },
    },
  };
  </script>
  